<?php
class ModelStockautoDocument extends Model {
	
	//生成入库单
	public function addStockIn($data){
		
		$warehouse = $data['warehouse_id'];

		$stockin = M('stock_in');
		$data['date_added'] = date('Y-m-d H:i:s');
		$mainid = $stockin->data($data)->add();

		$indetail = M('stock_in_detail');
		foreach($data['products'] as $value){
			
			$value['in_id'] = $mainid;
			$value['date_added'] = $data['date_added'];	
			$indetail->data($value)->add();
			
	  	}

	}

	//生成出库单
	public function addStockOut($data){
		
		$warehouse = $data['warehouse_id'];

		$stockout = M('stock_out');
		$data['date_added'] = date('Y-m-d H:i:s');
		$mainid = $stockout->data($data)->add();

		$outdetail = M('stock_out_detail');
		foreach($data['products'] as $value){
			
			$value['out_id'] = $mainid;
			$value['date_added'] = $data['date_added'];	
			$outdetail->data($value)->add();
			
	  	}

	}
	
	//改变库存可用数量 $warehouse仓库id, $code商品编码, $quantity数量, $type类型in是加out是减
	public function changeInventory($warehouse,$code,$quantity,$type,$trim_id=0){

		if($type == "in"){
			$qty = $quantity;
		}
		else if($type == "out"){
			$qty = -$quantity;
		}
		$now = date('Y-m-d H:i:s');

		$inventorydata = array(
			'warehouse_id' => $warehouse,
			'product_code' => $code,
			'account_quantity' => $qty,
			'available_quantity' => $qty,
			'safe_quantity' => 0,
			'date_added' => $now,
			'date_modified' => $now
		);
		
		$inventory = M('inventory');

		$where['warehouse_id'] = $warehouse;
		$where['product_code'] = $code;
		$id = $inventory->where($where)->select();

		if($id){
			$inventory->where(array('id' => $id[0]['id']))->setInc('account_quantity',$qty);
			$inventory->where(array('id' => $id[0]['id']))->setInc('available_quantity',$qty);
			$inventory->where(array('id' => $id[0]['id']))->setField('date_modified',$now);
            $inventoryPK = $id[0]['id'];
		}
		else{
			$inventoryPK = $inventory->data($inventorydata)->add();
		}

        /*
         * 入库单修改库存后保存库存变更日志
         * @author sonicsjh
         */
        if (0 != (int)$qty){
            $inventoryHistoryData = array(
                'inventory_id'  => $inventoryPK,//inventory表PK
                'product_code'  => $code,//商品编码（冗余字段）
                'warehouse_id'  => $warehouse,//仓库编号（冗余字段）
                'account_qty'   => (int)$qty,//财务数量变更（正+ 负-）
                'available_qty' => (int)$qty,//可用数量变更（正+ 负-）
                'comment'       => '损益单：'.$trim_id.' 完成。',//备注（入库单完成、损益单完成、出库单生成、出库单修改、出库单作废）
                'user_id'       => $this->user->getId(),//操作人PK
                'date_added'    => $now,//条目创建时间
            );
            M('inventory_history')->data($inventoryHistoryData)->add();
        }
	}

}